<template>
  <div class="login" v-loading="(loadingCode || loadingWord)">
    <TopAction fixed :show="[0, 2]" />
    <img src="local-media://logo.png" />
    <p>欢迎来到Mechat</p>
    <div class="phone">
      <el-popover v-model:visible="visible" :teleported="false" placement="bottom-start" :width="188" trigger="click">
        <template #reference>
          <div class="type">{{ selectCode }}</div>
        </template>
        <section class="areaCode noDrag">
          <div>
            <img src="local-media://icons/sm_search.png" alt="">
            <input type="text" v-model="searchCode">
          </div>
          <ul>
            <li v-for="item in result" @click="(visible = false, selectCode = item.code)">
              <span>{{ item?.city }}</span>
              <span>{{ item?.code }}</span>
            </li>
          </ul>
        </section>
      </el-popover>
      <span class="solide"></span>
      <input type="text" v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
    </div>
    <PassWord v-if="loginType === 0" v-model="form.password" :max="6" />
    <CountDown :max="6" :type="0" v-show="loginType === 1" :phone="form.phone" v-model="form.code" />
    <SubmitButton text="登录" @submit="submitInfo" />
    <div class="actions noDrag">
      <el-checkbox v-model="automaticLogin" class="noDrag" @change="changeAutoLogin">自动登录</el-checkbox>
      <div class="otherAction">
        <RouterLink to="/forgot">忘记密码</RouterLink>
      </div>
    </div>
    <button class="loginType" @click="loginType === 0 ? loginType = 1 : loginType = 0">{{
      loginEnum[loginType === 1 ? 0
        : 1]
    }}</button>
  </div>
</template>
<script setup>
import { RouterLink, useRouter } from 'vue-router'
import { login, loginByCode } from '@/server/login'
import { reactive, ref, inject, computed, onMounted } from 'vue'
import { useRequest } from 'vue-hooks-plus'
import { dexieInit } from '@/config/data'
import { ElMessage } from 'element-plus'
import CountDown from '@/components/Login/CountDown.vue'
import PassWord from '@/components/Login/PassWord.vue'
import SubmitButton from '@/components/Login/SubmitButton.vue'
import TopAction from '@/components/TopAction.vue'
import { enterMain } from "@/tool"
import { list } from '@/tool/data'
const loginEnum = {
  0: "密码登录",
  1: "短信快捷登录"
}
const selectCode = ref('+86')
const refreshUserInfo = inject('refreshUserInfo')
const automaticLogin = ref(false) // 自动登录
const loginType = ref(1)
const router = useRouter()
const form = reactive({
  password: "",
  phone: "",
  showWord: false,
  count: 0,
  code: "",
  platformType: 0
})

const loginSuccess = async (res) => {
  if (res?.token) {
    window.localStorage.setItem('Token', res.token)
    await refreshUserInfo()
    dexieInit(window.localStorage.getItem("userId"))
    router.replace('/')
    enterMain()
  } else {
    ElMessage({
      type: 'error',
      message: res?.msg,
      center: true,
    })
  }
}

//密码登录
const { run: loginAction, loading: loadingWord } = useRequest(async () => {
  if (form.phone === '') return Promise.reject({
    type: "warning",
    msg: '请输入手机号'
  })
  if (form.password === '') return Promise.reject({
    type: "warning",
    msg: "请输入密码"
  })
  await new Promise((rs) => {
    setTimeout(() => {
      rs(true)
    }, 2000);
  })
  return login(form)
}, {
  loadingDelay: 10,
  onSuccess: loginSuccess,
  onError: res => {
    ElMessage({
      type: res?.type,
      message: res?.msg,
      center: true
    })
  },
  manual: true
})



const { run: loginByCodeAction, loading: loadingCode } = useRequest(async () => {
  if (form.phone === '') return Promise.reject({
    type: "warning",
    msg: '请输入手机号'
  })
  if (form.code === '') {
    return Promise.reject({
      type: "warning",
      msg: '请输入验证码'
    })
  }
  await new Promise((rs) => {
    setTimeout(() => {
      rs(true)
    }, 2000);
  })
  return loginByCode({
    phone: form.phone,
    code: form.code,
    platformType: 0
  })
}, {
  onSuccess: loginSuccess,
  onError: res => {
    ElMessage({
      type: res?.type,
      message: res?.msg,
      center: true
    })
  },
  manual: true
})

const submitInfo = () => {
  loginType.value === 0 ? loginAction() : loginByCodeAction()
}


const visible = ref(false)

const searchCode = ref('')
const result = computed(() => {
  if (searchCode === '') return list
  return list.filter(v => v.city.includes(searchCode.value))
})

const changeAutoLogin = async () => {
  const autoState = await window.electronAPI.getLoginItemSettings()
  if (autoState?.openAtLogin) {
    window.electronAPI.closeAutoStart()
  } else {
    window.electronAPI.openAutoStart()
  }
  automaticLogin.value = !autoState.openAtLogin
}
onMounted(async () => {
  const autoState = await window.electronAPI.getLoginItemSettings()
  automaticLogin.value = autoState.openAtLogin
})
</script>
<style lang="less" scoped>
.login {
  width: 100%;
  height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;

  >p {
    margin-top: 37px;
    margin-bottom: 47px;
    font-size: 20px;

    font-weight: 500;
    color: #242424;
    line-height: 25px;
  }

  >img {
    width: 60px;
    height: 60px;
    object-fit: cover;
    margin-top: 100px;
  }

  .phone {
    background: #F4F4F4;
    width: 300px;
    display: flex;
    align-items: center;
    height: 48px;
    -webkit-app-region: no-drag;

    .type {
      font-size: 16px !important;

      font-weight: 500 !important;
      color: #242424 !important;
      line-height: 1;
      padding-left: 10px;
      cursor: pointer;
    }


    >input {
      background: #F4F4F4;
      font-size: 16px;

      font-weight: 500;
      color: #242424;
      line-height: 1;
      vertical-align: top;
      display: inline-block;
      padding-bottom: 2px;
      border: none;
      outline: none;
    }

    >span {
      margin: 0 10px;
      color: #787878;
    }
  }

  .actions {
    display: flex;
    justify-content: space-between;
    width: 300px;
    margin-top: 20px;
    font-size: 14px;

    .otherAction {
      display: flex;
      align-items: center;

      a {
        font-size: 14px;

        font-weight: 400;
        color: #787878;
        text-decoration: none;
      }

      >span {
        &:nth-child(2) {
          margin: 0 6px;
        }
      }
    }
  }

  .loginType {
    font-size: 16px;

    font-weight: 400;
    color: #2657B5;
    line-height: 25px;
    margin-top: 33px;
    border: none;
    background-color: transparent;
    cursor: pointer;
  }

  :deep(.el-popover) {
    padding: 0;
    border-radius: 10px;
  }
}

// .loginicons {
//   position: fixed;
//   left: 0;
//   top: 0;
//   margin: 0 !important;
//   cursor: pointer;
//   width: 90px !important;
//   height: 90px !important;
// }

.areaCode {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding-top: 16px;

  >div {

    border: 1px solid #ECECEC;
    height: 26px;
    border-radius: 18px;
    display: flex;
    align-items: center;
    width: 164px;
    margin: 0 auto;
    padding: 0 10px;


    >input {
      border: none;
      outline: none;
      height: 100%;
      flex: 1;
      text-indent: 6px;
      color: #787878;
      width: 90px;
    }

    >img {
      width: 14px;
      flex-shrink: 0;
      height: 15px;
    }
  }

  >ul {
    padding-bottom: 12px;
    margin-top: 12px;
    height: 220px;
    width: 100%;
    overflow-y: auto;

    &::-webkit-scrollbar {
      width: 5px;
      border-radius: 30px;
    }

    &::-webkit-scrollbar-thumb {
      height: 5px;
      width: 5px;
      background: rgba(161, 161, 161, 0.7);
    }

    >li {
      cursor: pointer;
      font-size: 14px;

      font-weight: 400;
      color: #242424;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 25px;
      padding: 0 12px;

      &:hover {
        background: rgba(1, 224, 235, 0.2);
      }
    }
  }
}

.solide {
  width: 1px;
  height: 14px;
  background-color: #3e3e3e;
}
</style>
